import { setUserConfig } from '@/api/config';
import { mapGetters } from 'vuex';
import { getParamDetail } from '@/api/system/param';
export default function (config) {
  return {
    provide() {
      return {
        // 这里需要调用被混入组件的表单实例reflesh 表格
        crud: this.$refs.crud
      };
    },
    data() {
      return {
        pageCode: this.$route.fullPath
      };
    },
    created() {
      this.setOptionColumn();
    },
    computed: {
      ...mapGetters(['userInfo'])
    },
    methods: {
      async getOptionColumn() {
        return [];
      },
      async setOptionColumn() {
        let column = await this.getOptionColumn();
        if (column.length > 0) {
          // 以下逻辑为了处理 column中的配置的事件丢失的问题
          const optionColumn = this._cloneDeep(this.option.column);
          let len = optionColumn.length;
          for (let i = 0; i < len; i++) {
            for (const key in optionColumn[i]) {
              if (!(key in column[i])) {
                column[i][key] = optionColumn[i][key];
              }
            }
          }
          // 参数管理字段特殊处理
          if (config && config.paramKey) {
            let find = column.find((col) => config.paramKey[col.prop]);
            let findIndex = column.findIndex((col) => config.paramKey[col.prop]);
            if (find) {
              getParamDetail({ paramKey: config.paramKey[find.prop] }).then((res) => {
                let data = res.data.data;
                if (this._get(data, 'paramValue') === 'false') {
                  column[findIndex].hide = true;
                } else {
                  column[findIndex].hide = false;
                }
                this.$set(this.option, 'column', column);
              });
            }
          } else {
            this.$set(this.option, 'column', column);
          }
        }
      },
      async handleSetUserConfig(val, code) {
        const { user_id } = this.userInfo;
        // 当有时发现新增编辑的字段不生效时，将column=[]再点击保存即可
        const params = { column: val, code, userId: user_id };
        try {
          const res = await setUserConfig(params);
          let msg = val.length == 0 ? '重置成功' : '保存成功';
          this.$message.success(msg);
        } catch (e) {
          console.warn(e);
        }
      }
    }
  };
}
